package com.hymjweb.demo.framework.util;

import org.apache.commons.beanutils.BeanUtils;

import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;

public class BeanUtil {

    public static void map2Bean(Map requestMap, Object oBean) {
        if (requestMap == null){
            return;
        }

        if (oBean == null){
            return;
        }

        Class cls = oBean.getClass();
        Method[] ms = cls.getMethods();
        if (ms.length <= 0) {
            return;
        }
        for (int i = 0; i < ms.length; i++) {
            Method m = ms[i];
            if (m.getName().startsWith("set")) {
                String id = getIdByMethodName(m.getName(), "set");

                if (!requestMap.containsKey(id)) {
                    // requset中没有此ID,不对bean赋值
                    continue;
                }
                String strValue = DataTypeUtil.toNotNullString(requestMap.get(id)).trim();
                Object objValue = requestMap.get(id);

                Class[] pTypes = m.getParameterTypes();
                Object[] oValues = null;
                if (pTypes.length > 0) {
                    Class c = pTypes[0];
                    oValues = new Object[1];
                    if ("java.lang.Integer".equals(c.getName()) || "int".equals(c.getName())) {
                        oValues[0] = getInteger(strValue);
                    } else if ("java.lang.Long".equals(c.getName()) || "long".equals(c.getName())) {
                        oValues[0] = getLong(strValue);
                    } else if ("java.math.BigDecimal".equals(c.getName())) {
                        oValues[0] = getBigDecimal(strValue);
                    } else if ("java.lang.Double".equals(c.getName()) || "double".equals(c.getName())) {
                        oValues[0] = getDouble(strValue);
                    } else if ("java.util.Date".equals(c.getName())) {
                        if (objValue instanceof String) {
                            oValues[0] = getDate(strValue);
                        } else if (objValue instanceof Date) {
                            oValues[0] = (Date)objValue;
                        }
                    } else if ("java.lang.String".equals(c.getName())) {
                        oValues[0] = strValue.toString();
                    } else{
                        System.out.println("有异常!!");
                    }
                }
                try {
                    m.invoke(oBean, oValues);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    // e.printStackTrace();
                }
            }
        }
    }

    /**
     * 根据方法名称获取属性名称，首字母小写返回
     * @param methodName 方法名
     * @param mType 方法名的前缀"get"、"set"
     * @return 如：getIdByMethodName("getName","get")="name"
     */
    private static String getIdByMethodName(String methodName, String mType) {
        methodName = DataTypeUtil.toNotNullString(methodName);
        mType = DataTypeUtil.toNotNullString(mType);
        if (methodName.length() <= 3){
            return "";
        }

        if (methodName.startsWith(mType)) {
            String temp = methodName.substring(3, methodName.length());
            if (!DataTypeUtil.isEmptyStr(temp)) {
                String t1 = temp.substring(0, 1).toLowerCase();
                temp = t1 + temp.substring(1, temp.length());
            }
            return temp;
        }
        return "";
    }

    /**
     * 转换数据库字段为java的属性，例如： CUSTOMER_NAME - > customerName, welfare_id -> welfareId
     * @param databaseColumnName
     * @return
     */
    public static String getAttributeName(String databaseColumnName) {
        String s = databaseColumnName.toLowerCase();
        String ret = "";
        String[] arr = s.split("_");
        for (int i = 0; i < arr.length; i++) {
            String s1 = "";
            if (i == 0) {
                s1 = arr[i].substring(0, 1).toLowerCase();
            } else {
                s1 = arr[i].substring(0, 1).toUpperCase();
            }
            String s2 = arr[i].substring(1, arr[i].length());
            ret += s1 + s2;
        }
        return ret;
    }

    /**
     * javabean属性名称转数据库字段名称,例如ztCode->ZT_CODE
     * @param attributeName javabean属性名称
     * @return 
     * @author admin
     * @serialData 2018年6月15日
     */
    public static String getDbColumnName(String attributeName) {
        if (DataTypeUtil.isEmptyStr(attributeName)){
            return attributeName;
        }

        char[] chars = attributeName.toCharArray();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < chars.length; i++) {
            char c = chars[i];
            if (c >= 'A' && c <= 'Z') {
                sb.append("_");
            }
            sb.append(String.valueOf(c).toUpperCase());
        }
        return sb.toString();
    }

    /**
     * javabean属性名称转数据库字段名称,例如ztCode->zt_code
     * @param pojoPropertyName
     * @return
     */
    public static String convertPropertyToDbColumnName(String pojoPropertyName){
        if(DataTypeUtil.isEmptyStr(pojoPropertyName)){
            return pojoPropertyName;
        }
        char[] chars=pojoPropertyName.toCharArray();
        StringBuffer sb=new StringBuffer();
        for(int i=0;i<chars.length;i++){
            char c=chars[i];
            if (c >= 'A' && c <= 'Z') {
                sb.append("_");
            }
            sb.append(String.valueOf(c));
        }
        return sb.toString().toLowerCase();
    }

    private static Integer getInteger(Object value) {
        if (DataTypeUtil.isEmptyStr(value)) {
            return null;
        } else {
            return new BigDecimal(value.toString()).intValue();
        }
    }

    public static Long getLong(Object value) {
        if (DataTypeUtil.isEmptyStr(value)) {
            return null;
        } else {
            return new BigDecimal(value.toString()).longValue();
        }
    }

    private static BigDecimal getBigDecimal(Object value) {
        if (DataTypeUtil.isEmptyStr(value)) {
            return null;
        } else {
            return new BigDecimal(value.toString());
        }
    }

    public static Date getDate(Object value) {
        if (DataTypeUtil.isEmptyStr(value)) {
            return null;
        }
        if (!DateUtil.isValidDate(value.toString())){
            return null;
        }

        try {
            return DateUtil.strToDate(value.toString());
        } catch (Exception e) {
        }
        return null;
    }

    private static Double getDouble(Object value) {
        if (DataTypeUtil.isEmptyStr(value)) {
            return null;
        } else {
            return new BigDecimal(value.toString()).doubleValue();
        }
    }

    public static String getGetMethodName(String propertieName) {
        if (DataTypeUtil.isEmptyStr(propertieName)){
            return null;
        }

        String ret = "get";
        ret += propertieName.substring(0, 1).toUpperCase();
        if (propertieName.length() > 1) {
            ret += propertieName.substring(1, propertieName.length());
        }
        return ret;
    }

    /**对象的所有属性拷贝
     * 
     * @param toObject 拷贝到的对象
     * @param fromObject 被拷贝的对象
     * @throws Exception 
     * @author 余伟
     * @serialData 2018年5月14日
     */
    public static void copyObject(Object toObject, Object fromObject) throws Exception {
        BeanUtils.copyProperties(toObject, fromObject);
    }

}
